﻿#if UNITY_EDITOR
using System.IO;
using UnityEditor;
using UnityEngine;
using StarForce;

[System.Reflection.Obfuscation(Exclude = true)]
public class ILRuntimeCLRBinding
{
    private const string DllPath = "Assets/Res/HotfixDLL/Hotfix.dll.bytes";
    
    // private const string ScriptAssembliesDir = "D:/unitystudy/MyHotPro/HotProj/bin/Debug";
    // private const string ScriptAssembliesDir = "D:/WorkCode/Unity/MyHotPro/HotProj/bin/Debug";
    // private const string CodeDir = "Assets/Res/HotfixDLL/";
    // private const string HotfixDll = "HotProj.dll";
    // private const string HotfixPdb = "HotProj.pdb";
    //
    //    
    // [MenuItem("ILRuntime/构建热更新DLL")]
    // public static void BuildHotfixDLL()
    // {
    //     File.Copy(Path.Combine(ScriptAssembliesDir, HotfixDll), Path.Combine(CodeDir, "Hotfix.dll.bytes"), true);
    //     File.Copy(Path.Combine(ScriptAssembliesDir, HotfixPdb), Path.Combine(CodeDir, "Hotfix.pdb.bytes"), true);
    //     Debug.Log("复制Hotfix.dll, Hotfix.pdb到Asset/Res/HotfixDLL完成");
    //     AssetDatabase.Refresh();
    // }
    //
    
    [MenuItem("ILRuntime/生成跨域继承适配器")]
    static void GenerateCrossbindAdapter()
    {
        //由于跨域继承特殊性太多，自动生成无法实现完全无副作用生成，所以这里提供的代码自动生成主要是给大家生成个初始模版，简化大家的工作
        //大多数情况直接使用自动生成的模版即可，如果遇到问题可以手动去修改生成后的文件，因此这里需要大家自行处理是否覆盖的问题

        // using(System.IO.StreamWriter sw = new System.IO.StreamWriter("Assets/Samples/ILRuntime/1.6.7/Demo/Scripts/Examples/04_Inheritance/InheritanceAdapter.cs"))
        // {
        //     sw.WriteLine(ILRuntime.Runtime.Enviorment.CrossBindingCodeGenerator.GenerateCrossBindingAdapterCode(typeof(TestClassBase), "ILRuntimeDemo"));
        // }

        AssetDatabase.Refresh();
    }
    
    [MenuItem("ILRuntime/通过自动分析热更DLL生成CLR绑定")]
    static void GenerateCLRBindingByAnalysis()
    {
        
        //用新的分析热更dll调用引用来生成绑定代码
        ILRuntime.Runtime.Enviorment.AppDomain domain = new ILRuntime.Runtime.Enviorment.AppDomain();
        using (System.IO.FileStream fs = new System.IO.FileStream(DllPath, System.IO.FileMode.Open, System.IO.FileAccess.Read))
        {
            domain.LoadAssembly(fs);

            //Crossbind Adapter is needed to generate the correct binding code
            InitILRuntime(domain);
            ILRuntime.Runtime.CLRBinding.BindingCodeGenerator.GenerateBindingCode(domain, "Assets/Scripts/Customs/ILRuntime/Generated");
        }

        AssetDatabase.Refresh();
    }

    static void InitILRuntime(ILRuntime.Runtime.Enviorment.AppDomain domain)
    {
        //这里需要注册所有热更DLL中用到的跨域继承Adapter，否则无法正确抓取引用
        domain.RegisterCrossBindingAdaptor(new CoroutineAdapter());
        domain.RegisterCrossBindingAdaptor(new IAsyncStateMachineAdaptor());
        domain.RegisterValueTypeBinder(typeof(Vector3), new Vector3Binder());
        domain.RegisterValueTypeBinder(typeof(Vector2), new Vector2Binder());
        domain.RegisterValueTypeBinder(typeof(Quaternion), new QuaternionBinder());
    }
}
#endif